<?php
/**
 * ClassName: CardPreferentialServer
 * Description:
 * @Author 周昌
 * @Create 2023/11/15 14:00
 */

namespace service\admin;


use libs\Tool;
use service\BaseService;
use think\Db;

class CardPreferentialService extends BaseService
{
    protected static $model='model\CardPreferentialModel';
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * #User: Administrator
     * #Time: 2023/11/23 17:30
     * #Author:周昌
     * #Description: 添加之前先删除旧数据
     * @param $data
     * @return array
     */
    public static function delBeforAdd($data)
    {
        $arr=[];
        $recharge_money=$data['recharge_money'];
        $gift_money=$data['gift_money'];
        $newArray = array_combine($recharge_money, $gift_money);
        foreach ($newArray as $k=>$v){
            $row=[];
            $row['recharge_money']=$k;
            $row['gift_money']=$v;
            $row['card_cate_id']=$data['card_cate_id'];
            $row['hospital_id']=$data['hospital_id'];
            $row['addtime']=time();
            $arr[]=$row;
        }
        Db::startTrans();
        try {
            $res=self::$model::delInfo(['card_cate_id'=>$data['card_cate_id']]);
            $result=self::$model::insertMore($arr);
            if($res!==false&&$result){
                Db::commit();
                return Tool::Success();
            }else{
                Db::rollback();
                return Tool::Error();
            }
        }catch (\Exception $exception){
            Db::rollback();
            return Tool::Error($exception->getMessage());
        }

    }

    /**
     * #User: Administrator
     * #Time: 2023/11/24 14:44
     * #Author:周昌
     * #Description:根据充值金额 获取赠送金额
     * @param $card_cate_id 会员卡分类id
     * @param $recharge_money 充值金额
     * @return int|mixed
     */
    public static function getGiftByRecharge($card_cate_id,$recharge_money)
    {
        $res=self::$model::field('recharge_money,gift_money')->where(['card_cate_id'=>$card_cate_id])
            ->order('recharge_money desc')->select()->toArray();
        $gift_money=0;
        if(empty($res)){
            return $gift_money;
        }
        $recharge_arr=array_column($res,'recharge_money');
        $gift_arr=array_column($res,'gift_money');
        $tmp=false;
        foreach ($recharge_arr as $k=>$v){
            if ($recharge_money>=$v){
                $tmp=$k;break;
            }
        }
        if($tmp===false){
            return $gift_money;
        }
        $gift_money=$gift_arr[$tmp];
        return $gift_money;
    }


}